<template>
  <div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-button type="primary" @click="addTable">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加角色
          </n-button>
        </template>

        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>

    <n-modal v-model:show="showModal_add" :show-icon="false" preset="dialog" title="新建角色">
      <n-form
        :model="formParams"
        :rules="rules"
        ref="formRef"
        label-placement="left"
        :label-width="80"
        class="py-4"
      >
        <n-form-item label="角色名称" path="name">
          <n-input placeholder="请输入角色名称" v-model:value="formParams.name" />
        </n-form-item>
        <n-form-item label="角色编号" path="code">
          <n-input placeholder="请输入角色编号" v-model:value="formParams.code" />
        </n-form-item>
        <n-form-item label="备注" path="remark">
          <n-input v-model:value="formParams.remark" />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal_add = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmAddForm">确定</n-button>
        </n-space>
      </template>
    </n-modal>

    <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="editRoleTitle">
      <div class="py-3 menu-list">
        <n-tree
          block-line
          cascade
          checkable
          key-field="id"
          :virtual-scroll="true"
          :data="treeData"
          :expandedKeys="expandedKeys"
          :checked-keys="checkedKeys"
          style="max-height: 950px; overflow: hidden"
          @update:checked-keys="checkedTree"
          @update:expanded-keys="onExpandedKeys"
        />
      </div>
      <template #action>
        <n-space>
          <n-button type="info" ghost icon-placement="left" @click="packHandle">
            全部{{ expandedKeys.length ? '收起' : '展开' }}
          </n-button>

          <n-button type="info" ghost icon-placement="left" @click="checkedAllHandle">
            全部{{ checkedAll ? '取消' : '选择' }}
          </n-button>
          <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, unref, h, onMounted } from 'vue';
import { useMessage, useDialog } from 'naive-ui';
import { BasicTable, TableAction } from '@/components/Table';
import { getRoleList, addRole, addRoleMenu, delRole } from '@/api/system/role';
import { getMenuList } from '@/api/system/menu';
import { columns } from './columns';
import { PlusOutlined } from '@vicons/antd';
import { getTreeAll, getTreeAllForId } from '@/utils';
import { useRouter } from 'vue-router';
import { ResultEnum } from '@/enums/httpEnum';

const router = useRouter();
const formRef: any = ref(null);
const message = useMessage();
const dialog = useDialog();
const actionRef = ref();

const showModal = ref(false);
const showModal_add = ref(false);
const formBtnLoading = ref(false);
const checkedAll = ref(false);
const editRoleTitle = ref('');
const treeData = ref([]);
const expandedKeys = ref([]);
const checkedKeys = ref([1, 2]);

const params = reactive({
  pageSize: 5,
  name: 'xiaoMa',
});

const rules = {
  name: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入角色名称',
  },
  code: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入角色编号',
  },
};
const formParams = reactive({
  name: '',
  code: '',
  remark: '',
});

const actionColumn = reactive({
  width: 250,
  title: '操作',
  key: 'action',
  fixed: 'right',
  render(record) {
    return h(TableAction, {
      style: 'button',
      actions: [
        {
          label: '菜单权限',
          onClick: handleMenuAuth.bind(null, record),
          // 根据业务控制是否显示 isShow 和 auth 是并且关系
          ifShow: () => {
            return true;
          },
          // 根据权限控制是否显示: 有权限，会显示，支持多个
          auth: ['basic_list'],
        },
        {
          label: '编辑',
          onClick: handleEdit.bind(null, record),
          ifShow: () => {
            return true;
          },
          auth: ['basic_list'],
        },
        {
          label: '删除',
          icon: 'ic:outline-delete-outline',
          onClick: handleDelete.bind(null, record),
          // 根据业务控制是否显示 isShow 和 auth 是并且关系
          ifShow: () => {
            return true;
          },
          // 根据权限控制是否显示: 有权限，会显示，支持多个
          auth: ['basic_list'],
        },
      ],
    });
  },
});

const loadDataTable = async (res: any) => {
  let _params = {
    ...unref(params),
    ...res,
  };
  return await getRoleList(_params);
};

function addTable() {
  showModal_add.value = true;
}

function onCheckedRow(rowKeys: any[]) {
  console.log(rowKeys);
}

function reloadTable() {
  actionRef.value.reload();
}

function confirmAddForm(e: any) {
  e.preventDefault();
  formBtnLoading.value = true;
  formRef.value.validate(async (errors) => {
    if (!errors) {
      const response = await addRole(formParams);
      const { result, code } = response;
      if (code === ResultEnum.SUCCESS) {
        message.success('新建成功');
        setTimeout(() => {
          showModal_add.value = false;
          reloadTable();
        });
      }
    } else {
      message.error('请填写完整信息');
    }
    formBtnLoading.value = false;
  });
}

const roleMenuParams = reactive({
  roleId: '',
  moduleIds: '',
});
function confirmForm(e: any) {
  e.preventDefault();
  formBtnLoading.value = true;

  roleMenuParams.moduleIds = checkedKeys.value.join();

  addRoleMenu(roleMenuParams);
  message.success('权限添加成功');
    setTimeout(() => {
      showModal.value = false;
      formBtnLoading.value = true;
      // reloadTable();
    });
}

function handleEdit(record: Recordable) {
  // console.log('点击了编辑', record);
  // router.push({ name: 'basic-info', params: { id: record.id } });
  Object.assign(formParams, record);
  showModal_add.value = true;
}

function handleDelete(record: Recordable) {
  // console.log('点击了删除', record);
  // message.info('点击了删除');
  dialog.info({
      title: '提示',
      content: `您想删除 ${record.name}`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        delRole(record.id);
        reloadTable();
        message.success('删除成功');
      },
      onNegativeClick: () => {},
    });
}

function handleMenuAuth(record: Recordable) {
  editRoleTitle.value = `分配 ${record.name} 的菜单权限`;
  checkedKeys.value = record.menuKeys;
  showModal.value = true;
  // console.log("------------record---------------" + record.id);
  roleMenuParams.roleId = record.id;
}

function checkedTree(keys) {
  checkedKeys.value = [checkedKeys.value, ...keys];
  // console.log("------------checkedKeys---------------" + checkedKeys.value);
}

function onExpandedKeys(keys) {
  expandedKeys.value = keys;
  console.log('------------onExpandedKeys---------------' + keys);
}

function packHandle() {
  if (expandedKeys.value.length) {
    expandedKeys.value = [];
  } else {
    expandedKeys.value = treeData.value.map((item: any) => item.id) as [];
  }
}

function checkedAllHandle() {
  if (!checkedAll.value) {
    checkedKeys.value = getTreeAllForId(treeData.value);
    checkedAll.value = true;
  } else {
    checkedKeys.value = [];
    checkedAll.value = false;
  }
}

onMounted(async () => {
  const treeMenuList = await getMenuList();
  expandedKeys.value = treeMenuList.map((item) => item.id);
  treeData.value = treeMenuList;
});
</script>

<style lang="less" scoped></style>
